"""Scheduler for automated daily code reviews."""

import logging
from typing import Optional

from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.triggers.cron import CronTrigger

from ..config import ConfigManager
from ..engine import ReviewEngine

logger = logging.getLogger(__name__)


class ReviewScheduler:
    """Scheduler for automated code reviews."""

    def __init__(self, config_manager: ConfigManager):
        """
        Initialize review scheduler.

        Args:
            config_manager: Configuration manager instance
        """
        self.config_manager = config_manager
        self.scheduler: Optional[BlockingScheduler] = None
        self.review_engine: Optional[ReviewEngine] = None

    def start(self) -> None:
        """Start the scheduler."""
        schedule_config = self.config_manager.get_schedule_config()

        if not schedule_config.get("enabled", True):
            logger.info("Scheduler is disabled in configuration")
            return

        # Initialize review engine
        self.review_engine = ReviewEngine(self.config_manager)

        # Create scheduler
        self.scheduler = BlockingScheduler()

        # Schedule daily review
        schedule_time = schedule_config.get("time", "09:00")
        timezone = schedule_config.get("timezone", "Asia/Shanghai")

        hour, minute = map(int, schedule_time.split(":"))

        self.scheduler.add_job(
            func=self.execute_review_task,
            trigger=CronTrigger(hour=hour, minute=minute, timezone=timezone),
            id="daily_review",
            name="Daily Code Review",
            replace_existing=True,
        )

        logger.info(f"Scheduler started. Daily review scheduled at {schedule_time} ({timezone})")

        try:
            self.scheduler.start()
        except (KeyboardInterrupt, SystemExit):
            logger.info("Scheduler stopped")

    def stop(self) -> None:
        """Stop the scheduler."""
        if self.scheduler:
            self.scheduler.shutdown()
            logger.info("Scheduler stopped")

    def execute_review_task(self) -> None:
        """Execute the review task."""
        logger.info("Starting scheduled review task")
        try:
            if self.review_engine:
                self.review_engine.run_review()
            else:
                self.review_engine = ReviewEngine(self.config_manager)
                self.review_engine.run_review()
        except Exception as e:
            logger.error(f"Error executing review task: {e}")

